import storage from "./storage";
import proxy from "./proxy";
import service from "./service";
import contextMenu from "./contextMenu";

(async () => {
  try {
    await service.getInitInfo()
  } catch (e) {
    await proxy.disable()
  } finally {
    await proxy.get()
  }
  chrome.tabs.onCreated.addListener(() => {
    contextMenu.setMenu();
  });
  await contextMenu.setMenu();
})();

const scopes = {
  storage, proxy, service, contextMenu
}
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  const {scope, action, params} = message
  const fn = scopes[scope]?.[action]
  if (fn) {
    Promise.resolve(fn(...(params || []))).then(data => {
      sendResponse(data)
    }).catch(() => {
      sendResponse()
    })
  } else {
    sendResponse()
  }
  return true
})
